#include "TextInputBox.h"
#include "base/Utility.h"
using namespace BlueprintScriptLibrary;

#define SetAttr(AttrName) SetAttribute(AttrName, ele->Attribute(AttrName));

void TextInputBox::ParseXmlElement(TiXmlElement* ele)
{
    this->name = ele->Attribute("name");
    SetAttr("pos")
        SetAttr("size")
        SetAttr("content")
        //  SetAttribute()

}
bool TextInputBox::SetAttribute(const char* attrName, const char* attrVal)
{
    if (attrVal == nullptr) return false;
    if (strcmp(attrName, "pos") == 0)
    {
        int x, y;
        sscanf_s(attrVal, "%d,%d", &x, &y);
        pos.x = x;
        pos.y = y;
        return true;
    }
    else   if (strcmp(attrName, "size") == 0)
    {
        int x, y;
        sscanf_s(attrVal, "%d,%d", &x, &y);
        size.x = x;
        size.y = y;
        return true;
    }
    else   if (strcmp(attrName, "content") == 0)
    {
        content = attrVal;
        return true;
    }

    return false;
}

void TextInputBox::OnDraw()
{
    glLineWidth(3);
    glColor3f(1., 1., 1.);
    std::wstring wstr = Utility::ConvertToWstring(content.val);
    TrueTypeFont* ttf = TrueTypeFont::GetInst();
    ttf->drawText(const_cast<wchar_t*>(wstr.data()), pos.x.val, pos.y.val+20, zIndex.val, size.x.val, size.y.val);

}

BlueprintScriptLibrary::Class* TextInputBox::GetClass()
{
    Array<NativeMembers> arrMember(4);
    Array<MethodPin> arrMethod(4, false);
    return BlueprintScriptLibrary::Class::BuildClassFromArray("TextInputBox", arrMember, arrMethod);
}
void TextInputBox::onKeyDown(int key, bool bCtrl, bool bShift, bool bAlt)
{
}
void TextInputBox::onKeyUp(int key)
{
    //  content.val.push_back(key);
    if (key >= SDL_SCANCODE_1 && key <= SDL_SCANCODE_0)
    {
        char offset = key - SDL_SCANCODE_1;
        if (offset == 10)
            content.val.push_back('0');
        else
            content.val.push_back('1' + offset);
    }
    if (key >= SDL_SCANCODE_A && key <= SDL_SCANCODE_Z)
    {
        char offset = key - SDL_SCANCODE_A;
        char rc = (IsCaps ? 'A' : 'a') + offset;
        content.val.push_back(rc);
    }
    /*if (key >= SDL_SCANCODE_a && key <= SDL_SCANCODE_Z)
    {
        content.val.push_back(key - SDL_SCANCODE_A);
    }*/
    if (SDL_SCANCODE_CAPSLOCK == key)
    {
        IsCaps = !IsCaps;
    } if (SDLK_CAPSLOCK == key)
    {
        IsCaps = !IsCaps;
    }
    if (SDL_SCANCODE_SPACE == key)
    {
        content.val.push_back(' ');
    }if (SDL_SCANCODE_SEMICOLON == key)
    {
        content.val.push_back(';');
    }if (SDL_SCANCODE_RETURN == key)
    {
        content.val.push_back('\r\n');
    }
    if (SDL_SCANCODE_BACKSPACE == key)
    {
        if (!content.val.empty())
            content.val.pop_back();
    }
    textChanged.Invoke(this, content);
}